package com.gpj.netty.demo.model;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.util.function.Consumer;

/**
 * @className STDNettyClient
 * @description TODO
 * @author GPJ
 * @date 2021/3/3 14:19
 * @version 1.0
 **/
@Slf4j
public class STDNettyClient {
	public static void run(Consumer<SocketChannel> consumer){
		NioEventLoopGroup group = new NioEventLoopGroup();

		try {
			Bootstrap bootstrap = new Bootstrap()
					.group(group)
					.channel(NioSocketChannel.class)
					.handler(new ChannelInitializer<SocketChannel>() {
						@Override
						protected void initChannel(SocketChannel socketChannel) {
							consumer.accept(socketChannel);
						}
					});
			ChannelFuture future = bootstrap.connect("127.0.0.1",9000).sync();
			future.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			log.error("netty客户端端启动失败:{}", e.getMessage(), e);
		}finally {
			group.shutdownGracefully();
		}
	}
}
